package controller;

import java.awt.Desktop;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JOptionPane;
import javax.swing.JTable;

import model.FileTableModel;
import model.GlobalParams;

import view.BrowsePanel;
import view.DiskContentPanel;
import view.MainFrame;

public class DiskContentPanelMouseListener implements MouseListener{
	
	public DiskContentPanelMouseListener(DiskContentPanel d, MainFrame f, BrowsePanel bf) {
		diskContentPanel = d;
		frame = f;
		browsePanel = bf;
	}
	
	@Override
	public void mouseClicked(MouseEvent arg0) {
		diskContentPanel.setActive();		
		frame.getMainPanel().changeBrowsePanel(browsePanel.getName());
		
		if (arg0.getClickCount() == 2) {
			int rowNumber = ((JTable)arg0.getSource()).getSelectedRow();
			File newFile = ((FileTableModel)((JTable)arg0.getSource()).getModel()).getSelectedRow(rowNumber);
			if(newFile.isDirectory()){
				((FileTableModel)((JTable)arg0.getSource()).getModel()).Clear();
				((FileTableModel)((JTable)arg0.getSource()).getModel()).Create(newFile);
				diskContentPanel.setActualFile(newFile);
				((FileTableModel)((JTable)arg0.getSource()).getModel()).fireTableDataChanged();
				
				frame.getMainPanel().getPrimary().getRelativePath().setText(newFile.getAbsolutePath());
				frame.getMainPanel().getPrimary().setStatusBar(newFile);
				frame.getMainPanel().getPrimary().getDiskContent().startScaning(newFile);
			}else {
				
				if (Desktop.isDesktopSupported()) {		
					try {
						Desktop.getDesktop().edit(newFile);
					} catch (IOException e) {			
						
						int option = JOptionPane.showConfirmDialog(frame, GlobalParams.getInstance().stringCollection.getOther_file_edit_error(), GlobalParams.getInstance().stringCollection.getOther_operation_manager(), JOptionPane.YES_NO_OPTION);
		                if(option != JOptionPane.YES_OPTION) 
		                	return;
		                else  {		                	
		                	try {  
		                        Runtime.getRuntime().exec("notepad.exe " + newFile.getAbsolutePath());  
		                        }  
		                      catch(Exception e1) {  
		                        e.printStackTrace();          
		                        } 		                	
		                }
		                	return;				
						
					}
				}
				
			}
		}		
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
	DiskContentPanel diskContentPanel;
	MainFrame frame;	
	BrowsePanel browsePanel;

}
